import 'package:flutter/material.dart';

/// 一个可自适应内容大小的自定义按钮组件.
///
/// 此按钮的样式可以通过 [CDTextButtonStyle] 进行配置.
/// 它的尺寸会根据 [child] 的大小和 [CDTextButtonStyle.padding] 自动调整.
class CDTextButton extends StatelessWidget {
  /// 按钮中显示的组件.
  final Widget child;

  /// 点击按钮时的回调函数. 如果为 null, 按钮将处于禁用状态.
  final VoidCallback? onPressed;

  /// 自定义按钮的样式.
  final CDTextButtonStyle? style;

  const CDTextButton({
    super.key,
    required this.child,
    this.onPressed,
    this.style,
  });

  /// 一个便捷的静态方法，用于创建 [CDTextButtonStyle].
  ///
  /// 这使得使用者可以轻松地覆盖部分默认样式，而无需手动创建完整的 [CDTextButtonStyle] 对象.
  static CDTextButtonStyle styleFrom({
    Color? backgroundColor,
    Color? disabledBackgroundColor,
    EdgeInsetsGeometry? padding,
    BorderRadius? borderRadius,
    TextStyle? textStyle,
  }) {
    return CDTextButtonStyle(
      backgroundColor: backgroundColor,
      disabledBackgroundColor: disabledBackgroundColor,
      padding: padding,
      borderRadius: borderRadius,
      textStyle: textStyle,
    );
  }

  @override
  Widget build(BuildContext context) {
    // 合并传入的样式与默认样式
    final effectiveStyle = style ?? const CDTextButtonStyle();
    final borderRadius = effectiveStyle.borderRadius ?? BorderRadius.circular(8.0);
    final backgroundColor = effectiveStyle.backgroundColor ?? Colors.blue;
    final disabledBackgroundColor = effectiveStyle.disabledBackgroundColor ?? Colors.grey;
    final padding = effectiveStyle.padding ?? const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0);
    final textStyle = effectiveStyle.textStyle ?? const TextStyle(color: Colors.white);

    final bool isEnabled = onPressed != null;

    return Ink(
      decoration: BoxDecoration(
        color: isEnabled ? backgroundColor : disabledBackgroundColor,
        borderRadius: borderRadius,
      ),
      child: InkWell(
        borderRadius: borderRadius,
        onTap: onPressed,
        child: Padding(
          padding: padding,
          // 使用 DefaultTextStyle, 以便 child 中的 Text 组件可以继承样式
          child: DefaultTextStyle(
            style: textStyle,
            child: Center(
              widthFactor: 1,
              heightFactor: 1,
              child: child,
            ),
          ),
        ),
      ),
    );
  }
}

/// 用于定义 [CDTextButton] 外观的样式类.
@immutable
class CDTextButtonStyle {
  /// 按钮的背景颜色.
  final Color? backgroundColor;

  /// 按钮在禁用状态下的背景颜色.
  final Color? disabledBackgroundColor;

  /// 按钮的内边距.
  final EdgeInsetsGeometry? padding;

  /// 按钮的边框圆角.
  final BorderRadius? borderRadius;

  /// 应用于按钮内 [Text] 组件的默认样式.
  final TextStyle? textStyle;

  const CDTextButtonStyle({
    this.backgroundColor,
    this.disabledBackgroundColor,
    this.padding,
    this.borderRadius,
    this.textStyle,
  });
}
